package com.hazens.myapplication;

public class ByteUtil {
    public static byte[] intToBytes(int res) {// 获得 Big endian byte 数组
        byte[] targets = new byte[4];
        targets[3] = (byte) (res & 0xff);// 最低位
        targets[2] = (byte) ((res >> 8) & 0xff);// 次低位
        targets[1] = (byte) ((res >> 16) & 0xff);// 次高位
        targets[0] = (byte) (res >>> 24);// 最高位,无符号右移。
        return targets;
    }

    public static int bytesToInt(byte[] data, final int offset) {
        return (data[3+offset] & 0xff) | ((data[2+offset] & 0xff) << 8)
                | ((data[1+offset] & 0xff) << 16) | ((data[offset] & 0xff) << 24);
    }

    public static byte[] shortTo4Bytes(int res) {// 获得 Big endian byte 数组
        byte[] targets = new byte[4];
        targets[3] = 0;// 最低位
        targets[2] = 0;// 次低位
        targets[1] = (byte) (res & 0xff);// 次高位
        targets[0] = (byte) ((res >> 8) & 0xff);// 最高位,无符号右移。
        return targets;
    }

    public static int bytesToShort(byte[] data, int offset) {
        return ((data[offset] & 0xff) << 8) | (data[++offset] & 0xff);
    }

    /**
     * 将一组byte数组按顺序拼接成一个byte数组
     */
    public static byte[] getData(byte[]... bytes) {
        int length = 0;
        int curCopyLength = 0;
        for (byte[] i : bytes) {
            length += i.length;
        }
        byte[] cmdData = new byte[length];
        for (byte[] aByte : bytes) {
            System.arraycopy(aByte, 0, cmdData, curCopyLength, aByte.length);
            curCopyLength += aByte.length;
        }
        return cmdData;
    }

    /**
     * 把字节数组转换成16进制字符串
     * @param bArray byte array
     * @return to String
     */
    public static String bytes2HexString(byte[] bArray) {
        StringBuilder sb = new StringBuilder(bArray.length);
        String sTemp;
        for (byte aBArray : bArray) {
            sTemp = Integer.toHexString(0xFF & aBArray);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static String bytes2String(byte[] b){
        String ret = "";
        for (byte aB : b) {
            ret += " " + aB;
        }
        return ret;
    }

    public static int bytesToInt(byte[] b) {
        return ((((b[0x3] & 0xff) | ((b[0x2] & 0xff) << 0x8)) | ((b[0x1] & 0xff) << 0x10)) | ((b[0x0] & 0xff) << 0x18));
    }

    public static short bytesToShort(byte[] b) {
        return (short)((b[0x1] & 0xff) | ((b[0x0] & 0xff) << 0x8));
    }

    public static byte[] trimmedData(byte[] data, int size) {
        if (data.length == size) {
            return data;
        }
        byte[] tmp = new byte[size];
        System.arraycopy(data, 0, tmp, 0, size);
        return tmp;
    }
}
